package com.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

/**
 * Created by reeveslee on 16/7/5.
 */
public class WechatSignatureController extends Controller {
    private static final Logger LOGGER = Logger.getLogger(WechatSignatureController.class);

    /**
     * 获取签名
     */
    public void getSignature() {

        String url = getPara("url");
        // 获取微信分享ticket
        String jsapiTicket = getWxShareTicket();

        // 获取时间戳
        long date = new Date().getTime();
        long timeStamp = date / 1000;

        String noncestr = "haoransun";

        String string1 = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + noncestr + "&timestamp=" + timeStamp + "&url=" + url;
        String signNature = DigestUtils.sha1Hex(string1);

        setAttr("timeStamp", timeStamp);
        setAttr("signature", signNature);
        setAttr("ticket", jsapiTicket);
        setAttr("accessToken", getAccessToken());

        HttpServletResponse response = getResponse();
        response.setHeader("Access-Control-Allow-Origin", "*");

        renderJson();
    }

    // 获取微信ticket
    public String getWxShareTicket() {
        String accessToken = getAccessToken();

        // 获取ticket
        String jsapiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        String jsapiTicketJson = loadJson(jsapiTicketUrl);
        JSONObject jsonObject2 = JSONObject.parseObject(jsapiTicketJson);
        return jsonObject2.getString("ticket");
    }


    // 获取access_token
    public String getAccessToken() {
        String appId = "wx651efc7e955f2b3c";
        String secret = "05a7e65039e5e736c2fd5c9c9865eef6";

        // 获取accessToken
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        String accessTokenJson = loadJson(accessTokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(accessTokenJson);
        String accessToken = jsonObject.getString("access_token");

        return accessToken;
    }

    /*
     * 工具类方法
    */
    public static String loadJson(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            LOGGER.error(e);
        } catch (IOException e) {
            LOGGER.error(e);
        }
        return json.toString();
    }
}
